/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.dao;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.chacha.model.LoginToken;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.WriteConcern;

/**
 * 
 *	@author: hejing
 *	@date: 2012-11-29-下午02:32:34
 */
public class LoginTokenDAO extends AbstractDAO implements DAO{
	private static final String COLLECTION_TOKEN="token";
	
	static{
		//创建索引，无就创建，有忽略
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		coll.ensureIndex(new BasicDBObject("userName",1), "idx_name",false);
		coll.ensureIndex(new BasicDBObject("token",1), "idx_token",false);
	}
	
	@Override
	public String getCollectionName() {
		return COLLECTION_TOKEN;
	}

	/**
	 * 根据令牌查询DBObject
	 * @param token
	 * @return
	 */
	private DBObject queryTokenByToken(String token){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("token").is(token).get();
		DBObject entity=coll.findOne(query);
		return entity;
	}
	
	/**
	 * 根据用户名查询DBObject
	 * @param token
	 * @return
	 */
	private DBObject queryTokenByUser(String userName){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("userName").is(userName).get();
		DBObject entity=coll.findOne(query);
		return entity;
	}
	
	/**
	 * 根据令牌获取logintoken
	 * @param token
	 * @return
	 */
	public LoginToken getToken(String token){
		DBObject entity=queryTokenByToken(token);
        if(entity != null) {
        	LoginToken loginToken=new LoginToken();
        	loginToken.fromDbObject(entity);
            return loginToken;
        } else {
            return null;
        }
	}
	/**
	 * 根据用户名获取logintoken
	 * @param token
	 * @return
	 */
	public LoginToken getTokenByUser(String userName){
		DBObject entity=queryTokenByUser(userName);
        if(entity != null) {
        	LoginToken loginToken=new LoginToken();
        	loginToken.fromDbObject(entity);
            return loginToken;
        } else {
            return null;
        }
	}
	/**
	 * 增加保存一个logintoken
	 * @param entity
	 * @return
	 */
	public LoginToken add(LoginToken entity){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		//LoginToken old=this.getTokenByUser(entity.getUserName());
		//if(old==null){
			entity.set_id(super.generateID());
			coll.insert(entity.toDbObject(),WriteConcern.NONE);
		//}else{
		//	old.setToken(entity.getToken());
		//	old.setTokenLifeTime(entity.getTokenLifeTime());
		//	update(old);
		//}
		return entity;
	}
	/**
	 * 根据用户名修改用户所属的logintoken
	 * @param entity
	 */
	public void update(LoginToken entity){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		coll.setWriteConcern(WriteConcern.NONE);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("userName").is(entity.getUserName()).get();
		coll.update(query,entity.toDbObject());
	}
	
	public void delete(String token){
		DBObject entity=queryTokenByToken(token);
		if(entity!=null){
			DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
			coll.remove(entity, WriteConcern.NONE);
		}
	}

	public void delete(LoginToken loginToken) {
		if(loginToken!=null){
			DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
			coll.remove(loginToken.toDbObject(), WriteConcern.NONE);
		}
		
	}
	
	/**
	 * 返回记录数
	 * @return
	 */
	public long count(){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		return coll.count();
	}
	/**
	 * 分页查询
	 * @param pageNum　每页记录数
	 * @param lastID　　上一页最后_id值
	 * @return
	 */
	public LinkedList<LoginToken> getPage(int pageNum,String lastID){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("_id").greaterThan(lastID).get();
		DBObject orderBy=new BasicDBObject("_id",1); //根据_id升序排列
		DBCursor cursor=coll.find().sort(orderBy).limit(pageNum);
		LinkedList<LoginToken> result=new LinkedList<LoginToken>();
		while(cursor.hasNext()){
			DBObject obj=cursor.next();
			LoginToken token=new LoginToken();
			token.fromDbObject(obj);
			result.add(token);
		}
		return result;
	}
	
	/**
	 * 分页查询
	 * @param pageNum　每页记录数
	 * @return
	 */
	public LinkedList<LoginToken> getFirstPage(int pageNum){
		DBCollection coll=connection.getCollection(COLLECTION_TOKEN);
		DBObject orderBy=new BasicDBObject("_id",1); //根据_id升序排列
		DBCursor cursor=coll.find().sort(orderBy).limit(pageNum);
		LinkedList<LoginToken> result=new LinkedList<LoginToken>();
		while(cursor.hasNext()){
			DBObject obj=cursor.next();
			LoginToken token=new LoginToken();
			token.fromDbObject(obj);
			result.add(token);
		}
		return result;
	}
	
}
